
import {asyncRoutes,resetRouter } from '../router/index'


// 将菜单信息转成对应的路由信息 动态添加
export function menusToRoutes(data) {
  console.log("菜单data",data)
  const result = []
  const children = []
  result.push({
    path: '/',
    component: () => import('../layout/index'),
    children,
  })

  data.forEach(item => {
    generateRoutes(children, item)
  })
  let redirect = ''
  if(children.length != 0){
    redirect = "/"+children[0].path
  }else{
    redirect = "/login"
  }

  result.push({path: '/', redirect: redirect},)
  // children.push({
  //   path: 'error',
  //   name: 'error',
  //   component: () => import('../components/Error.vue')
  // })

  //最后添加404页面 否则会在登陆成功后跳到404页面
  // result.push({
  //   path: '/downLoad',
  //   component: () => import('@/views/pdf/downLoad'),
  //   children,
  // })
  // result.push({
  //   path: '/report',
  //   component: () => import('@/views/pdf/performDownLoad'),
  //   children,
  // })
  result.push({
    path: '/404',
    component: () => import('@/views/404')
  })
  // result.push(
  //   {path: '*', redirect: '/404'},
  // )

  return result
}

function generateRoutes(children, item) {
  // console.log("generateRoutesItem",item)
  if (item.name) {
    if (item.menuFrom == item.menuTo) {
      if(asyncRoutes[item.name] != undefined){
        children.push(asyncRoutes[item.name])
      }
    } else {
      // children.push({
      //   path: item.name,
      //   name: item.name,
      //   text: item.text,
      //   component: () => import('@/views/tootherplatform/index'),
      //   meta: {
      //     title: item.text,
      //     menuFrom:item.menuFrom
      //   }
      // })
    }
  } else if (item.children) {
    item.children.forEach(e => {
      generateRoutes(children, e)
    })
  }
}

export function resetTokenAndClearUser() {
  // 退出登录 清除用户资料
  // localStorage.setItem('token', '')
  // localStorage.setItem('userImg', '')
  // localStorage.setItem('userName', '')
  // 重设路由
  resetRouter()
}


export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

export function dragControllerDiv(box,resize,left,right) {
  var box = document.getElementsByClassName(box);
  var resize = document.getElementsByClassName(resize);
  var left = document.getElementsByClassName(left);
  var right = document.getElementsByClassName(right);
  for (let i = 0; i < resize.length; i++) {
      // 鼠标按下事件
      resize[i].onmousedown = function (e) {
          resize[i].style.borderRight = '1px dotted #959595';
          resize[i].style.cursor = "e-resize";
          var startX = e.clientX;
          resize[i].left = resize[i].offsetLeft;
          // 鼠标拖动事件
          document.onmousemove = function (e) {
              var endX = e.clientX;
              var moveLen = resize[i].left + (endX - startX); // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
              var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

              if (moveLen < 195) moveLen = 195 // 左边区域的最小宽度为195px
              if (moveLen > 400) moveLen = 400
              // if (moveLen > maxT - 1000) moveLen = maxT - 1000; //右边区域最小宽度为1000px

              resize[i].style.left = moveLen; // 设置左侧区域的宽度

              for (let j = 0; j < left.length; j++) {
                  left[j].style.width = moveLen + 'px';
                  right[j].style.width = (box[i].clientWidth - moveLen - 10) + 'px';
              }
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
              resize[i].style.borderRight = '0px';
              document.onmousemove = null;
              document.onmouseup = null;
              resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
      };
  }
}

